window.addEventListener('load', function () {

    //判断用户是否登录
    isLogined();
    function isLogined() {
        var uid = localStorage.getItem('uid');
        var userName = document.querySelector('.card-info-userName');
        var point = document.querySelector('.Hright');
        var id = document.querySelector('.card-qr-userId');

        if (uid == null) {
            alert('请先登录')
            window.open('innisfree.html', '_self');
            userName.innerHTML = '';
            point.innerHTML = '';
            id.innerHTML = '';
        } else {
            if (window.XMLHttpRequest) {
                var xhr = new XMLHttpRequest();
            }
            xhr.open('get', ' http://localhost:3000/user?id=' + uid, false);
            xhr.send();
            if (xhr.status == 200 && xhr.readyState == 4) {
                var data = JSON.parse(xhr.responseText);
                userName.innerHTML = data[0].name;
                point.innerHTML = data[0].integral;
                id.innerHTML = 'No.' + data[0].id;
                // console.log(data);
            }
        }
    }

    //退出登录
    loginOut();
    function loginOut() {
        var outBtn = document.querySelector('.cardRight .logOut');
        outBtn.onclick = function () {
            window.localStorage.removeItem('uid');
            window.open('innisfree.html', '_self');
        }
    }

    //展示购物车
    cars();
    function cars() {
        //获取用户名
        var uid = localStorage.getItem('uid');
        //获取无数据的盒子
        var noData = document.querySelector('.noData');
        //获取有数据的盒子
        var haveData = document.querySelector('.haveData');

        //获取购物车盒子
        var carBox = document.querySelector('.carBox');

        carShow()
        function carShow() {
            if (window.XMLHttpRequest) {
                var xhr = new XMLHttpRequest();
            }
            xhr.open('get', 'http://localhost:3000/cars?uId=' + uid + '&_sort=id&_order=desc', false);
            // http://localhost:3000/uname/?_sort=id&_order=desc
            xhr.send();
            if (xhr.status == 200 && xhr.readyState == 4) {
                var data = JSON.parse(xhr.responseText);
                // console.log(data);
                //如果购物车中有数据就展示购物车
                if (data.length > 0) {
                    haveData.style.display = 'block';
                    noData.style.display = 'none';
                    //逐个展示商品
                    var str = '';
                    for (var i = 0; i < data.length; i++) {
                        var proId = data[i].productId;
                        xhr.open('get', 'http://localhost:3000/product?id=' + proId, false);
                        xhr.send();
                        if (xhr.status == 200 && xhr.readyState == 4) {
                            var proData = JSON.parse(xhr.responseText);
                            //单个商品的总价
                            // console.log(data[i]);
                            var totalPrice = proData[0].price * data[i].count;
                            str += `
                                <div class="orderItem" data-index="${data[i].id}">
                                <div class="onCheck">
                                    <input type="checkbox" class="checkItem">
                                </div>
                                <div class="orderImg">
                                    <img src="${proData[0].bigImg}" alt="">
                                </div>
                                <div class="orderInfo">
                                    <div class="infoTitle">${proData[0].name}</div>
                                    <div class="infoSize">${proData[0].size}</div>
                                    <div class="buyCount">
                                        <div class="price fl">
                                            <span class="priCon">¥</span>
                                            <span class="priCount">${proData[0].price}</span>
                                        </div>
                                        <div class="numVal fl">
                                            <i class="remove fl" data-index="${data[i].id}">-</i>
                                            <i class="add fr" data-index="${data[i].id}">+</i>
                                            <input type="text" value="${data[i].count}" class="number">
                                        </div>
                                    </div>
                                </div>
                                <div class="totalPriceBox">
                                    <span class="totex">总价：</span>
                                    <span class="pricon">¥</span>
                                    <span class="totalPrice">${totalPrice}</span>
                                </div>
                            </div>
                            `
                            carBox.innerHTML = str;
                        }

                    }

                    del();
                } else {
                    //如果没数据，就显示无数据
                    noData.style.display = 'block';
                    haveData.style.display = 'none';
                }

            }
            //点击修改购物车中的数量
            changeCount()
            function changeCount() {
                //合计按钮
                var allCheck = document.querySelector('.allCheck');
                //总价
                var totalPriceBox = document.querySelector('#hejiPrice');

                var carCount = 0;
                var removeN = document.querySelectorAll('.numVal .remove');
                var addN = document.querySelectorAll('.numVal .add');
                for (var i = 0; i < removeN.length; i++) {
                    //减少
                    removeN[i].onclick = function () {
                        // 获取数据库的数量
                        // 1.获取购物车id
                        var carId = this.dataset.index
                        // console.log(carId);
                        carCount = getCarCount(carId).count;
                        if (carCount > 1) {
                            carCount--;
                            console.log(carCount);
                            upCars(carId, uid, getCarCount(carId).productId, carCount);
                            carShow();
                            heji()
                            allCheck.checked = false;
                            totalPriceBox.innerHTML = ''
                        }
                        console.log(allCheck.checked);

                    }
                    //添加
                    addN[i].onclick = function () {
                        // 获取数据库的数量
                        // 1.获取购物车id
                        var carId = this.dataset.index
                        console.log(carId);
                        carCount = getCarCount(carId).count;
                        if (carCount < 100) {
                            carCount++;
                            console.log(carCount);
                            upCars(carId, uid, getCarCount(carId).productId, carCount);
                            carShow();
                            heji()
                            allCheck.checked = false;
                            totalPriceBox.innerHTML = ''
                        }
                    }

                    // 获取当前购物车的id和数量
                    function getCarCount(carId) {
                        if (window.XMLHttpRequest) {
                            var xhr = new XMLHttpRequest();
                        }
                        xhr.open('get', 'http://localhost:3000/cars?id=' + carId, false);
                        xhr.send();
                        if (xhr.status == 200 && xhr.readyState == 4) {
                            var carData = JSON.parse(xhr.responseText);
                            return carData[0];
                        }
                    }

                    //ajax修改购物车数量(要修改的购物车的id,用户的id,商品的id要修改的数量)
                    function upCars(carId, uid, productId, count) {
                        if (window.XMLHttpRequest) {
                            var xhr = new XMLHttpRequest();
                        }
                        xhr.open('put', 'http://localhost:3000/cars/' + carId, false);
                        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                        xhr.send(`uId=${uid}&productId=${productId}&count=${count}`);
                        if (xhr.status == 200 && xhr.readyState == 4) {
                            var data = JSON.parse(xhr.responseText);
                        }
                        console.log('修改了一条数据' + count);
                    }

                }



            }


        }

        //右键删除购物车
        del()
        function del(){
            var carItem=document.querySelectorAll('.orderItem');
            var flag=false;
            for(var i=0;i<carItem.length;i++){
                carItem[i].ondblclick = function () {
                    flag=confirm('确定删除该商品吗？');
                    if(flag){
                        var id=this.dataset.index;
                        console.log(id);
                        if (window.XMLHttpRequest) {
                            var xhr = new XMLHttpRequest();
                        }
                        xhr.open('delete', 'http://localhost:3000/cars/'+id, false);
                        xhr.send();
                        if (xhr.status == 200 && xhr.readyState == 4) {
                            carShow();
                            flag=false;
                        }
                    }
                }
            }
        }

        heji();
        //计算合计
        function heji() {
            // 获取所有的复选框
            var checkItems = document.querySelectorAll('.checkItem');
            //获取所有的总价
            var totals = document.querySelectorAll('.totalPrice');
            var totalPriceBox = document.querySelector('#hejiPrice');
            //获取全选按钮
            var allCheck = document.querySelector('.allCheck');


            //计算和
            function chk() {
                var sum = 0;
                for (var i = 0; i < checkItems.length; i++) {
                    if (checkItems[i].checked) {
                        sum += parseFloat(totals[i].innerHTML);
                    }
                }
                // console.log(totalPriceBox);
                totalPriceBox.innerHTML = sum;
            }

            //单选
            for (var i = 0; i < checkItems.length; i++) {
                checkItems[i].onclick = function () {
                    // console.log(this.checked);
                    allCheck.checked = false;
                    chk();
                }
            }

            //全选
            allCheck.onclick = function () {
                for (var i = 0; i < checkItems.length; i++) {
                    checkItems[i].checked = this.checked;
                }
                chk();
            }
        }

    }
})